package com.atguigu.crowd.funding.service.impl;

import com.atguigu.crowd.funding.config.SecurityAdmin;
import com.atguigu.crowd.funding.entity.Admin;
import com.atguigu.crowd.funding.entity.AdminExample;
import com.atguigu.crowd.funding.entity.Auth;
import com.atguigu.crowd.funding.entity.Role;
import com.atguigu.crowd.funding.mapper.AdminMapper;
import com.atguigu.crowd.funding.mapper.AuthMapper;
import com.atguigu.crowd.funding.mapper.RoleMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author hftang
 * @date 2019-11-02 15:26
 * @desc
 */
@Service
public class CrowdFundingUserDetailsService implements UserDetailsService {
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    RoleMapper roleMapper;
    @Autowired
    AuthMapper authMapper;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        AdminExample exampleAdmin = new AdminExample();
        AdminExample.Criteria criteria = exampleAdmin.createCriteria();
        criteria.andLoginAcctEqualTo(username);
        List<Admin> adminList = this.adminMapper.selectByExample(exampleAdmin);
        if (CollectionUtils.isEmpty(adminList)) {
            return null;
        }
        Admin admin = adminList.get(0);

        //然后获取到他的所有角色 和 权限

        List<GrantedAuthority> authorities = new ArrayList<>();

        Integer adminId = admin.getId();
        //获取角色
        List<Role> roleList = this.roleMapper.selectAssignedRoleList(adminId);

        if (!CollectionUtils.isEmpty(roleList)) {
            for (Role role : roleList) {

                String roleName = "ROLE_" + role.getName();
                authorities.add(new SimpleGrantedAuthority(roleName));
            }
        }

        //获取权限
        List<Auth> authList = this.authMapper.selectAuthListByAdminId(adminId);

        if (!CollectionUtils.isEmpty(authList)) {

            for (Auth auth : authList) {

                String authName = auth.getName();
                if (StringUtils.isBlank(authName)) {
                    continue;
                }
                authorities.add(new SimpleGrantedAuthority(authName));

            }
        }


        return new SecurityAdmin(admin, authorities);
    }
}
